<!-- 上传图片 -->
<template>
  <view class='m-upload'>
    <view class="label">
      <text>{{label}}</text>
    </view>
    <view class="image">
      <view class="image-list" v-for="item in imageList" :key="item.id">
        <image v-if="!previewFlag" class="delete" src="/static/upload/delete.png" @click="tapDelete(item.id)">
        </image>
        <image class="image-data" :src="item.path" mode="aspectFill" @click="tapPreview(item.path)"></image>
      </view>
      <image v-if="!previewFlag" class="upload-btn-icon" src="/static/upload/upload.png"
        @click="tapUpload(businessType)"></image>

      <!-- 确定上传到服务器 -->
      <button type="primary" @click="submitImg(businessType)">{{businessType}}</button>
    </view>
  </view>
</template>

<script>
  export default {
    props: {
      label: {
        type: String,
        default: '上传图片'
      },
      businessType: {
        type: String,
        default: '01' //业务类型 01-考勤打卡 02-审批 03-到点留痕
      },
      previewFlag: {
        type: Boolean,
        default: false //预览模式不显示删除图标和上传图标
      },
      //初始显示数据
      initlist: {
        type: Array,
        default: function() {
          return [];
        }
      }
    },
    data() {
      return {
        imgNum: 0, //一共选中了多少张照片,用来限制本次最大上传数量
        imageList: [],
        serverUrl: "http://127.0.0.1:8080/file/filesUpload?businessType=", //要上传的图片的服务器地址
      }
    },
    created() {

    },
    //页面渲染完成
    mounted() {
      for (let item of this.initlist) {
        let obj = {
          ...item,
        }
        this.imageList.push(obj);
      }
    },
    watch: {
      initlist(nVal, oVal) {
        for (let item of nVal) {
          let obj = {
            ...item,
          }
          this.imageList.push(obj);
        }

      },
    },
    /**
     * 计算属性
     */
    computed: {

    },
    methods: {
      tapDelete(id) {
        let that = this;
        //console.log(`删除${id}`);
        //先移除显示的图片，在删除服务器端的图片
        let images = that.imageList;
        let indexImage = images.findIndex(n => n.id == id);
        if (indexImage != -1) {
          that.imageList.splice(indexImage, 1); //删除当前数组对象

          //调用接口，删除图片
          console.log('删除图片', id);
          that.$emit('myEvent', that.imageList)
        }
      },
      tapPreview(path) {
        console.log(`当前图片${path}`);
        let images = [];
        for (let item of this.imageList) {
          images.push(item.path);
        }
        // 预览图片
        uni.previewImage({
          current: path,
          urls: images,
          indicator: 'default',
          loop: true,
        });

      },

      tapUpload() {
        let that = this;

        uni.chooseMessageFile({
          count: 9, //默认9
          sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
          success: function(res) {
            // 遍历要上传的图片临时地址，进行上传
            for (let item of res.tempFiles) {

              that.imageList.push({
                path: item.path,
              })



              // 判断本次最多上传多少照片
              that.imgNum++;
              if (that.imgNum > 9) {
                that.imgNum = 9;
                uni.showToast({
                  icon: "none",
                  title: "上传的图片最多不能超过9张",
                });
                return;
              }

              console.log("that.imageList", that.imageList)
              that.$emit('myEvent', that.imageList)
            }
          }
        });
      },

      // 确定上传图片，传到服务器
      submitImg(businessType) {
        console.log("businessType->", businessType)
        let that = this;
        // let token = uni.getStorageSync(TOKEN_KEY) || ''

        let token =
          "eyJhbGciOiJIUzI1NiJ9.eyJtYW5nZUNvbSI6Ijg2MjEiLCJyb2xlS2V5IjoibnFyb2xlIiwiY29tQ29kZSI6Ijg2MjEwMDAwMDAwMDAwMDAxIiwidXNlcklkIjoiemhhbmdzYW4iLCJpYXQiOjE2NTI1MzAyMjIsImV4cCI6MTY1MzczOTgyMn0.F-L-r2f4PkmgBaKkRp1GSo6Jerp-oHDpCr2HI4bdJ-M";
        // 遍历要上传的图片临时地址，进行上传
        that.imageList.map((val) => {
          console.log("val-》", val)
          uni.uploadFile({
            url: that.serverUrl + businessType, //服务器地址
            filePath: val.path, //存在本地要上传的临时图片地址
            name: "file", //名字可以随便写
            header: {
              Authorization: "Bearer " + token,
              "Content-Type": "multipart/form-data",
            },
            formData: {
              execId: "execId",
              record: "record2",
              num: "num3",
            },
            success(res) {

              //上传成功的回调函数
              console.log(res, "上传成功");
              uni.showToast({
                icon: "none",
                title: "上传成功",
              });

            },
            fail(res) {
              console.log(res, "上传失败");
              // that.imageList.splice(indexImage, 1); //删除当前数组对象
              uni.showToast({
                icon: "none",
                title: "上传失败",
              });
            },

          });

        });
      },

    }
  }
</script>

<style lang="scss" scoped>
  .m-upload {

    .label {
      padding: 20rpx;
      background-color: #eeeeee;
      font-size: 28rpx;
      font-weight: bold;
      color: #303133;
    }

    .image {
      display: flex;
      flex-wrap: wrap;
      background-color: #FFFFFF;
      padding: 20rpx;

      .image-list {
        position: relative;

        .delete {
          position: absolute;
          z-index: 10;
          width: 40rpx;
          height: 40rpx;
          top: 0;
          right: 0;
        }

        .image-data {
          width: 216rpx;
          height: 216rpx;
          padding: 10rpx 10rpx 0 10rpx;
        }

        // .upload-progress {
        //  width: 176rpx;
        //  padding: 0 10rpx;
        //  position: absolute;
        //  z-index: 20;
        //  height: 20rpx;
        //  left: 20rpx;
        //  bottom: 140rpx;
        // }

        // .upload-mask {
        //  position: absolute;
        //  z-index: 19;
        //  width: 216rpx;
        //  height: 216rpx;
        //  top: 10rpx;
        //  left: 10rpx;
        //  background-color: #000000;
        //  opacity: 0.6;
        // }
      }

      .upload-btn-icon {
        width: 216rpx;
        height: 216rpx;
        padding: 10rpx 10rpx 0 10rpx;
      }
    }
  }
</style>